/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.deschutter.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.impl.SessionFactoryImpl;

/**
 *
 * @author berten
 */
public class GenericHibernateDAO<T, ID extends Serializable>
        implements GenericDAO<T, ID> {

    private Class<T> persistentClass;
  private SessionFactoryImpl sessionFactory;

    public SessionFactoryImpl getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactoryImpl sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public GenericHibernateDAO() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
                                .getGenericSuperclass()).getActualTypeArguments()[0];
     }



    public Class<T> getPersistentClass() {
        return persistentClass;
    }

    @SuppressWarnings("unchecked")
    public T findById(ID id, boolean lock) {
        T entity;
        if (lock)
            entity = (T) getSessionFactory().openSession().load(getPersistentClass(), id, LockMode.UPGRADE);
        else
            entity = (T) getSessionFactory().openSession().load(getPersistentClass(), id);

        return entity;
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
        return findByCriteria();
    }

    @SuppressWarnings("unchecked")
    public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
        Criteria crit = getSessionFactory().openSession().createCriteria(getPersistentClass());
        Example example =  Example.create(exampleInstance);
        for (String exclude : excludeProperty) {
            example.excludeProperty(exclude);
        }
        crit.add(example);
        return crit.list();
    }

    @SuppressWarnings("unchecked")
    public T makePersistent(T entity) {
        getSessionFactory().openSession().saveOrUpdate(entity);
        return entity;
    }

    public void makeTransient(T entity) {
        getSessionFactory().openSession().delete(entity);
    }

    public void flush() {
        getSessionFactory().openSession().flush();
    }

    public void clear() {
        getSessionFactory().openSession().clear();
    }

    /**
     * Use this inside subclasses as a convenience method.
     */
    @SuppressWarnings("unchecked")
    public List<T> findByCriteria(Criterion... criterion) {
        Criteria crit = getSessionFactory().openSession().createCriteria(getPersistentClass());
        for (Criterion c : criterion) {
            crit.add(c);
        }
        return crit.list();
   }

    public List<T> findByExample(T exampleInstance) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}
